package com.climber.android.auth.ui

import android.app.Activity
import android.content.Intent
import com.climber.android.auth.R
import com.climber.android.auth.api.AuthService
import com.climber.android.auth.entity.SocialRegisterCompleteEvent
import com.climber.android.commonres.app.service.CoreService
import com.climber.android.commonres.app.service.OTPRequestType
import com.climber.android.commonres.helper.onClick
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.ui.dialog.CommonVerticalActionsDialog
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonsdk.api.APIError
import com.climber.android.commonsdk.api.ApiObserver
import com.climber.android.commonsdk.api.GlobalErrorProcessor
import com.climber.android.commonsdk.api.entity.APIResponse
import com.climber.android.commonsdk.event.BusProvider
import com.climber.android.commonsdk.helper.openActivity
import com.climber.android.commonsdk.util.APIDataHelper
import io.ganguo.library.mvp.http.RxSchedulers
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.RxLifecycleUtils
import io.ganguo.library.mvp.util.UIUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.auth_activity_input_sms_code.*

/**
 * Created by Mikes at 2020-03-31 21:34
 */
class AuthInputSmsCodeActivity : BaseMVPActivity<IPresenter>(){
    private val otpRequestType : OTPRequestType by lazy {
        OTPRequestType.valueOf(intent.getStringExtra("otpRequestType"))
    }

    private val phoneNumber : String by lazy {
        intent.getStringExtra("phoneNumber")
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.auth_activity_input_sms_code

    override fun initView() {
        when(otpRequestType){
            OTPRequestType.BindNewPhone ->{
                nextBtn.setText(R.string.common_ok)
            }
            OTPRequestType.ModifyPhone ->{
                nextBtn.setText(R.string.common_next_step)
            }
            OTPRequestType.ModifyPassword ->{
                nextBtn.setText(R.string.common_next_step)
            }
            OTPRequestType.FindPassword ->{
                nextBtn.setText(R.string.common_next_step)
            }
            OTPRequestType.RegisterPhone ->{
                nextBtn.setText(R.string.common_next_step)
            }
        }

        subTitleLabel.text = String.format("我们已向 %s 发送了短信验证码", phoneNumber)
    }

    override fun initListener() {
        etSMSCode.setInputCallBack {
            nextBtn.isEnabled = true
        }

        nextBtn.onClick {
            when(otpRequestType){
                OTPRequestType.BindNewPhone ->{
                    // 绑定新手机号
                    doBindPhone()
                }
                OTPRequestType.ModifyPhone ->{
                    // 验证旧手机号，验证通过，绑定新手机号
                    doCheckOldPhone()
                }
                OTPRequestType.ModifyPassword ->{
                    openActivity(Intent(this, AuthModifyPasswordActivity::class.java)
                            .putExtra("otpRequestType", OTPRequestType.ModifyPassword.name)
                            .putExtras(wrapperResult()))

                    setResult(Activity.RESULT_OK, wrapperResult())
                    finish()
                }
                OTPRequestType.FindPassword ->{
                    // 重新设置新密码
                    openActivity(Intent(this, AuthModifyPasswordActivity::class.java)
                            .putExtra("otpRequestType", OTPRequestType.FindPassword.name)
                            .putExtras(wrapperResult()))

                    setResult(Activity.RESULT_OK, wrapperResult())
                    finish()
                }
                OTPRequestType.RegisterPhone ->{
                    doCheckPhoneIsRegistered()
                }
            }
        }
    }

    private fun wrapperResult() : Intent =
            Intent().putExtra("phoneNumber", phoneNumber)
                    .putExtra("smsCode", etSMSCode.getPsw())

    override fun initData() {}

    private fun doBindPhone(){
        AuthService.authServiceAPI.issueModifyPhoneNumber(APIDataHelper.generateRequestBody(mapOf(
                "mobile" to phoneNumber,
                "code" to etSMSCode.getPsw()
        )))
                .compose(RxSchedulers.networkRequest())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe { UIHelper.showLoading(this, null) }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>(){
                    override fun success(apiResponse: APIResponse) {
                        UIHelper.hideLoading()

                        // 验证 用户输入的验证码，通过即提醒用户 成功绑定新手机号
                        CommonVerticalActionsDialog.generate {
                            setTitle("修改成功")

                            setContent("恭喜您已成功绑定新的手机号码")

                            setConfirmBtnLabel(UIUtils.getString(R.string.common_ok)) {
                                setResult(Activity.RESULT_OK, wrapperResult())
                                finish()
                            }

                            create()
                        }.show(supportFragmentManager, "")
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }

    private fun doCheckOldPhone(){
        CoreService.coreServiceAPI.issueVerifyOTPCode(APIDataHelper.generateRequestBody(mapOf(
                "mobile" to phoneNumber,
                "code" to etSMSCode.getPsw(),
                "type" to "4"
        )))
                .compose(RxSchedulers.networkRequest())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe { UIHelper.showLoading(this, null) }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>(){
                    override fun success(apiResponse: APIResponse) {
                        UIHelper.hideLoading()

                        AuthInputPhoneActivity.openPage(this@AuthInputSmsCodeActivity, OTPRequestType.BindNewPhone)

                        setResult(Activity.RESULT_OK, wrapperResult())
                        finish()
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }

    /**
     * 检查该手机号是否已绑定
     */
    private fun doCheckPhoneIsRegistered(){
        /**
         * 1.校验输入的手机号，已在系统内注册，但是未绑定，则自动绑定该手机号，返回20000
         * 2.校验输入的手机号，已在系统内注册，但已绑定其他账号，提示用户"此手机号已绑定其他账号" 返回20002
         * 3.校验输入的手机号，未在系统内注册，则进入下一个页面要求用户输入昵称，密码，完成社交账号注册。同时需要自动绑定该手机号。 返回20003
         */
        AuthService.authServiceAPI.issueVerifyMobileIsRegistered(APIDataHelper.generateRequestBody(mapOf(
                "mobile" to phoneNumber
        )))
                .compose(RxSchedulers.networkRequest())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe { UIHelper.showLoading(this, null) }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<APIResponse>(){
                    override fun success(apiResponse: APIResponse) {
                        UIHelper.hideLoading()

                        BusProvider.getInstance().post(SocialRegisterCompleteEvent())

                        setResult(Activity.RESULT_OK, wrapperResult())
                        finish()
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()

                        if(apiError is APIError.ServerError){
                            when(apiError.errorCode){
                                20003 ->{
                                    openActivity(Intent(this@AuthInputSmsCodeActivity, AuthSocialSignUpActivity::class.java)
                                            .putExtra("phoneNumber", phoneNumber)
                                            .putExtra("socialRequest", intent.getSerializableExtra("socialRequest")))
                                }
                            }
                        }
                    }
                })
    }
}